package com.ellecity06.cwhiskymall.ui.newer

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.loadState.LoadState
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.ellecity06.common.adapter.CustomLoadMoreAdapter
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.finishRefresh
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.theme
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.NewerDetailGoodAdapter
import com.ellecity06.cwhiskymall.adapter.NewerHeaderAdapter
import com.ellecity06.cwhiskymall.databinding.ActivityNewerGoodBinding
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import com.gyf.immersionbar.ktx.immersionBar

/**
 * @author ellecity06
 * @time 2024/11/13 14:53
 * @des
 */
class NewerGoodActivity : BaseMvvmActivity<ActivityNewerGoodBinding, NewerGoodViewModel>(),
    SwipeRefreshLayout.OnRefreshListener, TrailingLoadStateAdapter.OnTrailingListener {
    private val categoryId: Int by lazy { intent.getIntExtra("categoryId", 0) }
    private val adapter: NewerDetailGoodAdapter by lazy { NewerDetailGoodAdapter() }
    override val userBaseTitle: Boolean
        get() = false

    override fun inflateBinding(): ActivityNewerGoodBinding {
        return ActivityNewerGoodBinding.inflate(layoutInflater)
    }

    override fun initImmersionBar() {
        immersionBar {
            titleBar(binding.toolBar)
            statusBarDarkFont(false)
        }
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is NewerGoodState.RefreshSuccess -> {
                    adapter.submitList(it.list)
                    binding.refreshLayout.finishRefresh()
                    if (it.hasMore) {
                        adapterHelper.trailingLoadState = LoadState.NotLoading(false)
                    } else {
                        adapterHelper.trailingLoadState = LoadState.None
                    }
                    binding.ivEmpty.visibility = if (it.list.isEmpty()) View.VISIBLE else View.GONE
                }

                is NewerGoodState.LoadMoreSuccess -> {
                    adapter.addAll(it.list)
                    adapterHelper.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                }

                is NewerGoodState.LoadError -> {
                    binding.refreshLayout.finishRefresh()
                }

                is NewerGoodState.NoMore -> {
                    binding.refreshLayout.finishRefresh()
                    adapterHelper.trailingLoadState = LoadState.None
                }

                else -> {}
            }
        }
    }

    private lateinit var adapterHelper: QuickAdapterHelper
    @SuppressLint("SuspiciousIndentation")
    override fun initialize(savedInstanceState: Bundle?) {
        // 根据用户信息设置不同背景
        if (!UserStorage.isVip()) {
            binding.content.setBackgroundResource(R.color.main_color)

        } else {
            binding.content.setBackgroundResource(R.color.newer_bg_2)
        }
        binding.ivBack.setOnClickListener { finish() }
        binding.refreshLayout.theme()
        binding.rvGood.layoutManager = LinearLayoutManager(this)
        val loadMoreAdapter = CustomLoadMoreAdapter()
        loadMoreAdapter.setOnLoadMoreListener(this)
        adapter.isEmptyViewEnable = true
        binding.rvGood.isNestedScrollingEnabled = true
        adapter.setEmptyViewLayout(this, R.layout.layout_empty_view)
        adapter.animationEnable = true

        adapter.setItemAnimation(BaseQuickAdapter.AnimationType.ScaleIn)
        adapterHelper = QuickAdapterHelper.Builder(adapter)
            .setTrailingLoadStateAdapter(loadMoreAdapter)
            .build()

        binding.rvGood.adapter = adapterHelper.adapter
            adapterHelper.addBeforeAdapter(NewerHeaderAdapter())
        onRefresh()
    }

    override fun initEvent() {
        binding.refreshLayout.setOnRefreshListener(this)
        adapter.setOnItemClickListener { _, _, position ->
            val item = adapter.getItem(position)
            WebHelper.goodDetails(this, item?.id)
        }
    }

    override fun onRefresh() {
        refresh()
    }

    private fun refresh() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(NewerGoodIntent.FetchGood(categoryId))
        }
    }

    private fun loadMore() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(NewerGoodIntent.LoadMore(categoryId))
        }
    }

    override fun onFailRetry() {
        loadMore()
    }

    override fun onLoad() {
        loadMore()
        logD("开始加载更多")
    }

}